package com.teamblueplus.websearch;

import java.io.BufferedReader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.teamblueplus.R;


public class GoogleSearchAPIActivity extends Activity implements OnItemClickListener{
   
	
	//private ListView listViewImages;
	private GridView gridViewImages;
	private EditText txtSearchText;	
	
    private GridViewImageAdapter adapter;
    private ArrayList<Object> listImages;
	private Activity activity;
	
	String strSearch = null;
	ImageView image_view;
	Bitmap bitmap;
	
	private String message="";
    private	Handler mProgressHandler;
    private GoogleImageBean bean;
    
    private String imagePath;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview);
        
        activity = this;
        
        //listViewImages = (ListView) findViewById(R.id.lviewImages);
        gridViewImages = (GridView) findViewById(R.id.gridView1);
        
        txtSearchText = (EditText) findViewById(R.id.txtViewSearch);
        image_view = (ImageView)findViewById(R.id.imageview);
      
    }
   
    public void loadImage(String image_location){
    	 
          URL imageURL = null;
          
          try {
        	  imageURL = new URL(image_location);
          	} 
          
          catch (MalformedURLException e) {
              e.printStackTrace();
          	}
          
          try {
        	  HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
        	  connection.setDoInput(true);
        	  connection.connect();
              InputStream inputStream = connection.getInputStream();
               
              bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
              image_view.setImageBitmap(bitmap);
          }
          catch (IOException e) {
              
               e.printStackTrace();
          }
     }
    
   public class getImagesTask extends AsyncTask<Void, Void, Void>
   {
	   JSONObject json,json2, json3;
	   ProgressDialog dialog;
	   
	   @Override
	   protected void onPreExecute() {
		   // TODO Auto-generated method stub
		   super.onPreExecute();
		   
		   dialog = ProgressDialog.show(GoogleSearchAPIActivity.this, "", "Please wait...");
	   }
	   
	   @Override
	   protected Void doInBackground(Void... params) {
		   // TODO Auto-generated method stub
		   
		   URL url;
		   try {
			   
			   url = new URL("https://www.googleapis.com/customsearch/v1?key=AIzaSyCHwXZj58aLnfCQr7qk0jd_z8lm6u6d9E8&cx=003040558399435156120:7t46paakcnu&q="+ strSearch + "&searchType=image&fileType=jpg&imgSize=medium&alt=json");
			   //url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
			   //	"v=1.0&q="+strSearch+"&rsz=8&imgsz=huge&start=1&key=AIzaSyCHwXZj58aLnfCQr7qk0jd_z8lm6u6d9E8"); 
			   //&key=ABQIAAAADxhJjHRvoeM2WF3nxP5rCBRcGWwHZ9XQzXD3SWg04vbBlJ3EWxR0b0NVPhZ4xmhQVm3uUBvvRF-VAA&userip=192.168.0.172");

		   URLConnection connection = url.openConnection();
		   //connection.addRequestProperty("Referer", "http://technotalkative.com");
		   
		   String line;
		   StringBuilder builder = new StringBuilder();
		   BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		   while((line = reader.readLine()) != null) {
			  
			   builder.append(line);
			  
		   }
		   
		   url = new URL("https://www.googleapis.com/customsearch/v1?key=AIzaSyCHwXZj58aLnfCQr7qk0jd_z8lm6u6d9E8&cx=003040558399435156120:7t46paakcnu&q=" + strSearch + "flower&searchType=image&start=11&fileType=jpg&imgSize=medium&alt=json");

//		   url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
//				   	"v=1.0&q="+strSearch+"&rsz=8&imgsz=huge&start=9&key=AIzaSyCHwXZj58aLnfCQr7qk0jd_z8lm6u6d9E8"); 
		   connection = url.openConnection();
		   StringBuilder builder2 = new StringBuilder();
		    reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		  
		    while((line = reader.readLine()) != null) {
			   builder2.append(line);
		
		   }

		   json = new JSONObject(builder.toString());
		   json2 = new JSONObject(builder2.toString());

		   } catch (MalformedURLException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   return null;
	   }
	   
	   @Override
	   protected void onPostExecute(Void result) {
		   // TODO Auto-generated method stub
		   super.onPostExecute(result);
		   
		   if(dialog.isShowing())
		   {
			   dialog.dismiss();
		   }
		   
		   try {

			   JSONArray resultArray = json.getJSONArray("items");

			   JSONArray resultArray2 = json.getJSONArray("items");

			   listImages = getImageList(resultArray, resultArray2);
			   
			   SetListViewAdapter(listImages);
		   } catch (JSONException e) {
			e.printStackTrace();
		}
		   
	   }
   }
   
   public ArrayList<Object> getImageList(JSONArray resultArray, JSONArray resultArray2)
   {
	   ArrayList<Object> listImages = new ArrayList<Object>();
	   GoogleImageBean bean;

		try 
		{
			for(int y=0; y<3; y++)
			{
			 int size=0;
			 if(y==0) size=resultArray.length();
			 if(y==1) size=resultArray2.length();
			 for(int i=0; i<size; i++)
			 {
				JSONObject obj = null;
				if(y==0)
					obj = resultArray.getJSONObject(i);
				else if(y==1)
					obj = resultArray2.getJSONObject(i);
				bean = new GoogleImageBean();
			   
				bean.setTitle(obj.getString("title"));
				bean.setThumbUrl(obj.getString("link"));
				
				Log.d("h2", "Thumb URL => "+obj.getString("link"));
				
				listImages.add(bean);
			   
			 }
			}
			return listImages;
		 }
		 catch (JSONException e) 
		 {
				// TODO Auto-generated catch block
				e.printStackTrace();
		 }
		 
		 return null;
	}
   
   public void SetListViewAdapter(ArrayList<Object> images)
   {
//	   adapter = new ListViewImageAdapter(activity, images);
//	   listViewImages.setAdapter(adapter);
//	   listViewImages.setOnItemClickListener(this);
	   
	   adapter = new GridViewImageAdapter(activity, images);
	   gridViewImages.setAdapter(adapter);
	   gridViewImages.setOnItemClickListener(this);
	   
   }
   
   public void btnSearchClick(View v)
   {
	   strSearch = txtSearchText.getText().toString();
	   strSearch = Uri.encode(strSearch);
	   
	   new getImagesTask().execute();
   }
   
   public int downloadImageFromWeb(String urlAddress)
   {
	   try {
           URL url = new URL(urlAddress);
          // File file = new File(fileName);

           long startTime = System.currentTimeMillis();
           URLConnection ucon = url.openConnection();
           InputStream is = ucon.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);
           /*
            * Read bytes to the Buffer until there is nothing more to read(-1).
            */
           ByteArrayBuffer baf = new ByteArrayBuffer(50);
           int current = 0;
           while ((current = bis.read()) != -1) {
                   baf.append((byte) current);
           }
           File sdCard = Environment.getExternalStorageDirectory();
           File dir = new File (sdCard.getAbsolutePath() + "/dimages");
           dir.mkdirs();
           
           this.imagePath = System.currentTimeMillis() + "webImage.jpg";
           File file = new File(dir, imagePath);
           FileOutputStream fos = new FileOutputStream(file);
           fos.write(baf.toByteArray());
           fos.close();
           
	   		} catch (IOException e) {
	   			Log.e("Error", "IOException::downloadImageFromWeb");
	   			return 0;
	   		}
	  return 1;
   }

    @Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
    {
		
	   //  image.setImageBitmap( adapter.imageLoader.cache.get(bean.getThumbUrl()));
	   //Object o = listViewImages.getAdapter().getItem(arg2);
	   //Object o = listViewImages.getItemAtPosition(arg2);
       Object o = gridViewImages.getItemAtPosition(arg2);
    		   
    		 
	   bean = (GoogleImageBean) o;
	   //test to show the image using url
	   //this.loadImage(bean.getThumbUrl());
	   
	   mProgressHandler = new Handler() {
	       
           public void handleMessage(Message msg) {
               super.handleMessage(msg);
               
               message = "successfully downloaded image";
               Toast.makeText(activity.getApplicationContext(), message, Toast.LENGTH_SHORT).show();		
           }
       };
       
       Thread t = new Thread(new Runnable()
  		{
	    	public void run()
	    	{
	       	  if(downloadImageFromWeb(bean.getThumbUrl())==1)
	    		   mProgressHandler.sendEmptyMessage(0);	
	       	  
	       	 Intent intent = new Intent();
	       	 intent.putExtra("path", imagePath);
	       	 
	       	 setResult(RESULT_OK, intent);
	       	 finish();
	       	 
//	       	 Intent myIntent = new Intent(GoogleSearchAPIActivity.this,
//	  				ImageViewer.class); 
//	       	
//	       	 myIntent.putExtra("imagepath", GoogleSearchAPIActivity.this.imagePath);
//			 GoogleSearchAPIActivity.this.startActivityForResult(myIntent, 0);
	    	}
  		});
	    t.start();
	    
	  

	}
   
   
}